package spring.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import spring.event.AsyncEventPublisher;
import spring.event.RandomEvent;
import spring.event.RegisterEvent;

/**
 * @author huu
 * @create 2025-08-25-14:32
 */

@RestController
public class LoginController {

    //spring容器
    @Autowired
    private ApplicationContext applicationContext;

    //事件发布器
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    //事件广播器
    @Autowired
    private ApplicationEventMulticaster multicaster;

    // @PostConstruct 注解用于在依赖注入完成后执行初始化方法
    // 通常用于执行一些初始化逻辑，比如发布事件或启动定时任务等
    // 注意：需要导入 javax.annotation.PostConstruct 包
    //但PostConstruct中不能发布事件


    @GetMapping("/login")
    public String login() {
        RandomEvent event = new RandomEvent("randomevent初始化");
        applicationEventPublisher.publishEvent(event);
        return "ok";
    }

    @Autowired
    private AsyncEventPublisher asyncEventPublisher;
    @GetMapping("/register")
    //TODO 异步事件我这用的注解偷懒实现的，自定义线程池好像才是正道
    public String register(String user) {
        System.out.println("register start at: " + System.currentTimeMillis());
        RegisterEvent event = new RegisterEvent(user);
        //applicationEventPublisher.publishEvent(event);
        multicaster.multicastEvent(event);
        //asyncEventPublisher.publishEvent( event);
        System.out.println("register end at: " + System.currentTimeMillis());
        return "ok";
    }
}
